package com.eastseeway.radioproject.work;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.eastseeway.radioproject.entities.BaseResponse;
import com.eastseeway.radioproject.retrofit.RetrofitClient;
import com.eastseeway.radioproject.utils.SPHelper;
import com.eastseeway.radioproject.utils.SaveHelper;
import com.eastseeway.radioproject.utils.TimeFormatter;
import com.eastseeway.radioproject.utils.TimeUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileFilter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UploadLogWorker extends Worker {

    private final Context mContext;

    public UploadLogWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        mContext = context;
    }

    @NonNull
    @Override
    public Result doWork() {
        String[] workKeys = getInputData().getStringArray("work_key");
        String beginDateString = workKeys[0];
        String endDateString = workKeys[1];
        Log.e("12121",beginDateString+" :日期: "+endDateString);

        try {
            Date beginDate = TimeFormatter.yyyy_MM_ddHH_mm_ss.parse(beginDateString);
            Date endDate = TimeFormatter.yyyy_MM_ddHH_mm_ss.parse(endDateString);

            RequestBody deviceid = RequestBody.create(MediaType.parse("text/plain"), SPHelper.getDeviceId(mContext));
            RequestBody remark = RequestBody.create(MediaType.parse("text/plain"), "file description");
            File[] files = new File(SaveHelper.createLogDirectory()).listFiles();
            if (files != null && files.length >= 0) {
                for (File file : files) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    Date newDate = TimeFormatter.yyyyMMdd.parse(file.getName());
                    boolean effectiveDate = TimeUtils.isEffectiveDate(newDate, beginDate, endDate);
                    if (!effectiveDate) {
                        continue;
                    }
                    RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                    MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), fileBody);
                    RetrofitClient.getInstance().getServiceApi().uploadLogFile(filePart,deviceid,remark).enqueue(new Callback<BaseResponse>() {
                        @Override
                        public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                            Log.e("12121","upload result: "+new Gson().toJson(response.body()));
                        }
                        @Override
                        public void onFailure(Call<BaseResponse> call, Throwable throwable) {
                            Log.e("12121", "upload failed ");
                        }
                    });
                }
            }

        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }
}
